package net.csdn.business.mirror.listen;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.constant.CommonConstants;
import net.csdn.business.common.utils.BusinessUtil;
import net.csdn.business.common.utils.JsonUtil;
import net.csdn.business.mirror.SpringBeanUtil;
import net.csdn.business.mirror.entity.bo.MirrorMqBodyBO;
import net.csdn.business.mirror.enums.MirrorMqEnum;
import net.csdn.business.mirror.service.MqProjectChangeImplement;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Slf4j
@Component
public class AliProjectMirrorMessageListener implements MessageListener {

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        MDC.put(CommonConstants.TRACE_ID, BusinessUtil.genTraceId());
        try {

            MirrorMqBodyBO body = JSON.parseObject(new String(message.getBody()), MirrorMqBodyBO.class);
            MirrorMqEnum.EventType eventTypeEnum = MirrorMqEnum.EventType.parse(body.getEventType());
            if (Objects.isNull(eventTypeEnum)) {
                return Action.CommitMessage;
            }
            log.info("consumer message body: {}", new String(message.getBody()));
            MqProjectChangeImplement projectChangeImplement = SpringBeanUtil.getBean(eventTypeEnum.getProjectChangeImplementService());
            projectChangeImplement.exec(body);
        } catch (Exception e) {
            log.error("consumer mirror message error. msg:{} ex:{}", JsonUtil.toJsonString(message), JsonUtil.toJsonString(e));
            return Action.ReconsumeLater;
        } finally {
            MDC.remove(CommonConstants.TRACE_ID);
        }
        return Action.CommitMessage;
    }

}